<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Archive;
use App\Category;
use App\Http\Requests;
use \Michelf\MarkdownExtra;
use App\Http\Controllers\FileController;

class ArchiveController extends Controller
{
    //
    function __construct(Request $request){
        $FileController = new FileController();
        $FileController->uptoken();

        $this->admin = $request->session()->get('admin', false);
        $this->data = ['admin' => $this->admin,
                    'categorys' => Category::all(),
                    'uptoken' => $FileController->uptoken(),
                    ];
    }
    public function index(){
    	$archives = Archive::latest()->paginate(10);
        $this->data['archives'] =$archives;
    	return view('blog.archives',$this->data);
    }
    public function show($id){
    	$archive = Archive::findorFail($id);
        $this->data['archive'] =$archive;
    	return view('blog.archiveShow',$this->data);
    }
    public function edit($id){
        if (!$this->admin){ return '小样，你不是主人！';}
    	$archive = Archive::findorFail($id);
        $this->data['archive'] =$archive;
    	return view('blog.archiveEdit',$this->data);
    }
    public function create(){
        if (!$this->admin){ return '小样，你不是主人！';}
    	return view('blog.archiveCreate',$this->data);
    }
    public function store(Request $request){
        if (!$this->admin){ return '小样，你不是主人！';}
    	$input = $request->all();
    	$input['text'] = trim($input['text']);
        if (empty(trim($input['title'])) || empty($input['text'])){
            return '你啥都没写，好不好？';
        }
    	$input['html'] = MarkdownExtra::defaultTransform($input['text']);
    	$input['user_id'] = 1;
    	Archive::create($input);
    	return redirect('/archive');
    }
    public function update(Request $request){
    	$input = $request->all();
    	$id = $input['archive_id'];
    	$archive = Archive::findorFail($id);
    	$update = ['category_id' => $input['category_id'],
            'text'=>trim($input['text']),
    		'html' => MarkdownExtra::defaultTransform(trim($input['text']))];
    	$archive->update($update);
    	return redirect('/archive/'.$id);
    }
    public function delete($id){
        if (!$this->admin){ return '小样，你不是主人！';}
        $archive = Archive::findorFail($id);
        $archive->delete();
        return redirect('/archive');
    }
}
